package com.ruoyi.health.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.health.domain.User;
import com.ruoyi.health.mapper.UserMapper;
import com.ruoyi.health.service.IRegisterService;
import com.ruoyi.health.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisCache redisCache;  //验证码在redis

    public String register(RegisterBody registerBody)
    {
        String msg = "";
        // 前台用户注册：手机号+密码
        String phone = registerBody.getPhone();
        String password = registerBody.getPassword();
        // 封装注册用户 user
        User user = new User();
        user.setPhone(phone);
        user.setUsername("用户"+phone);  //默认的用户名是：用户+手机号

        // 验证码
        // 使用1234可以跳过验证码
        if(!registerBody.getCode().equals("1234")){
            validateCode(phone, registerBody.getCode(), registerBody.getUuid());
        }



        if (StringUtils.isEmpty(phone))
        {
            msg = "注册手机号不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (phone.length()!= 11)
        {
            msg = "中国手机号必须11位";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH  || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在6到20个字符之间";
        }
        else if (userService.checkPhoneUnique(phone)>0)
        {
            msg = "注册失败，手机号"+ phone +"已占用";
        }
        else
        {

            user.setPassword(SecurityUtils.encryptPassword(password));
            int row = userService.insertUser(user);
            if (!(row>0))
            {
                msg = "注册失败,请联系管理人员";
            }
            // 记录注册日志不要了
            // else
            // {
            //     AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.REGISTER, MessageUtils.message("user.register.success")));
            // }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param phone 用户名（实际是手机号）
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCode(String phone, String code, String uuid)
    {
        // 用户输入的验证码
        String verifyKey = CacheConstants.FRONT_CODE_KEY + StringUtils.nvl(uuid, "");
        // 从缓存中取出验证码 captcha
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }


}
